package com.service;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @program: sch-diy-parent
 * @description:
 * @author: sch
 * @create: 2020-12-12 22:33
 **/
@ServerEndpoint(value = "/simpleWebSocket")
public class SimpleWebSocketTest {
    //在线数量
    private static int onlineCount = 0;
    //存储Mywebsocket对象
    private static CopyOnWriteArraySet<SimpleWebSocketTest> webSocketSet = new CopyOnWriteArraySet();
    //建立会话的session
    private Session session;

    /**
     * 连接建立成功的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        this.addOnlinCount(); //在线数+1
        System.out.println("有新连接加入，当前在线人数:" + getOnlineCount());

    }


    /**
     * 关闭连接
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        this.subOnlineCount();//在线人数-1
        System.out.println("有人离开，当前在线人数:" + getOnlineCount());
    }

    /**
     * 收到消息后处理
     */
    @OnMessage
    public void onMessagge(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        //群发消息
        for (SimpleWebSocketTest item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }

    /**
     * 发送消息
     * @param message
     */
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    private void subOnlineCount() {
        onlineCount -= 1;
    }

    private String getOnlineCount() {
        return String.valueOf(onlineCount);
    }

    private void addOnlinCount() {
        onlineCount += 1;
    }


}
